# coding: utf-8

"""
    共用的方法
"""

import base64
import random
import uuid

import requests
from Crypto.Cipher import AES
from django.core.mail import send_mail
from redis import StrictRedis
from HuanFaXing import settings
from tools.common_vars import phone_vcode_redis_key


def aes_decrypt(key, data):
    """
    function: 后端AES解密
    :param key: 密钥
    :param data: 待解密的数据(前端加密过的)
    :return: 明文
    """

    key = key.encode("utf8")
    data = base64.b64decode(data)
    cipher = AES.new(key, AES.MODE_ECB)

    text_decrypted = cipher.decrypt(data)
    text_decrypted = text_decrypted.decode('utf8')
    return text_decrypted


def gen_vcode(length=6):
    """
    function: 生成验证码, 默认长度为6
    :param length: 默认长度为6
    :return: 6位数字验证码字符串
    """

    return ''.join(random.choices('0123456789', k=length))


def send_verification_mail(to_who, user_id):
    """
    function: 发邮件
    :param to_who: 用户的邮箱
    :param user_id: 用户的id
    :return:
    """

    uuid_str = uuid.uuid1()
    # 将token信息写入redis
    sr = StrictRedis()
    sr.set(user_id, str(uuid_str))

    # todo 上线服务器之后, 服务器网址要改
    html_message = "<a href='http://127.0.0.1:8000/users/activate_mailbox/?id={}&token={}'>{}</a>".format(
        user_id, uuid_str, "请点击此激活链接......")

    subject = "换发型-账号激活邮件"
    send_mail(subject, "", settings.EMAIL_FROM, [to_who], html_message=html_message)


def do_phone_verification(phone_vcode):
    """
    function: 对表单提交的手机验证码进行验证
    :param phone_vcode:
    :return:
    """

    sr = StrictRedis()
    redis_vcode = sr.get(phone_vcode_redis_key).decode()  # 加上decode, 是为了将bytes转换为string
    if phone_vcode == redis_vcode:
        return True
    else:
        return False


def send_phone_vcode(code, mobile_phone_num):
    """
    todo function: 执行手机号码验证
    :param code: 验证码
    :param mobile_phone_num: 手机号
    :return:
    """

    api_key = "d59ea01ec20e55e12dad40448f15f51b"  # 云片网-账户设置-子账号管理
    single_send_url = 'https://sms.yunpian.com/v2/sms/single_send.json'

    # 将验证码存入redis
    sr = StrictRedis()
    sr.set(phone_vcode_redis_key, code)

    param = {
        'apikey': api_key,
        'mobile': mobile_phone_num,
        'text': '【换发型-秀出自己】您的验证码是{code}。如非本人操作，请忽略本短信'.format(code=code)
    }

    # text必须要跟云片后台的模板内容 保持一致，不然发送不出去！
    return requests.post(single_send_url, data=param)
